// pages/detail/detail.js
import { CouponCenterType, ShoppingWay } from "../../core/enum"
import { Cart } from "../../models/cart"
import { CartItem } from "../../models/cart-item"
import { Coupon } from "../../models/coupon"
import { SaleExplain } from "../../models/sale-explain"
import { Spu } from "../../models/spu"
import { getWindowHeightRpx } from "../../utils/system"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showRealm: false,
        cartItemCount: 0

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        const pid = options.pid
        const spu = await Spu.getDetail(pid)
        console.log(spu);
        const explain = await SaleExplain.getFixed()
        const coupons = await Coupon.getTop2CouponsByCategory(spu.category_id)

        const windowsHieght = await getWindowHeightRpx()
        const h = windowsHieght - 100


        this.setData({
            spu,
            explain,
            h,
            coupons
        })

    },
    onAddToCart(event) {
        this.setData({
            showRealm: true,
            orderWay: ShoppingWay.CART
        })
    },
    OnShopping(event) {
        const chooseSku = event.detail.sku
        const skuCount = event.detail.skuCount
        if (event.detail.orderWay === ShoppingWay.CART) {
            const cart = new Cart()
            const cartItem = new CartItem(chooseSku, skuCount)
            cart.addItem(cartItem)

            this.updateCartItemCount()
        }
        if (event.detail.orderWay === ShoppingWay.BUY) {
            wx.navigateTo({
                url: `/pages/order/order?sku_id=${chooseSku.id}&count=${skuCount}&way=${ShoppingWay.BUY}`,
            });
        }
    },

    updateCartItemCount() {
        const cart = new Cart()
        this.setData({
            cartItemCount: cart.getCartItemCount(),
            showRealm: false
        })
    },
    onBuy(event) {
        this.setData({
            showRealm: true,
            orderWay: ShoppingWay.BUY
        })
    },
    onGotoHome(event) {
        wx.switchTab({
            url: '/pages/home/home',

        });
    },
    onGotoCart(event) {
        wx.switchTab({
            url: '/pages/cart/cart',

        });
    },
    onGoToCouponCenter(event) {
        const type = CouponCenterType.SPU_CATEGORY
        const cid = this.data.spu.category_id
        wx.navigateTo({
            url: `/pages/coupon/coupon?cid=${cid}&type=${type}`,
        });
    },

    onSpecChange(event) {
        this.setData({
            specs: event.detail
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },


    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})